package com.byx.passwordedittext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.reflect.Field;

/**
 * PasswordEditText
 *
 * @author Superb
 * @date 2021/1/30 20:25
 */
public class PasswordEditText extends LinearLayout {
    private EditText editText;
    private ImageView showPwd;
    private ImageView clearPwd;

    private boolean hidePwd;

    public PasswordEditText(Context context) {
        super(context);
        init(context,null);
    }

    @SuppressLint("ClickableViewAccessibility")
    public PasswordEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public PasswordEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init(@NonNull Context context, @Nullable AttributeSet attrs){
        LayoutInflater.from(context).inflate(R.layout.password_edit_text_layout_main,this,true);
        editText=findViewById(R.id.edit_text);
        showPwd=findViewById(R.id.show_password);
        clearPwd=findViewById(R.id.clear_password);

        if(null != attrs){
            TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.PasswordEditText);
            CharSequence s=attributes.getText(R.styleable.PasswordEditText_hint);
            if (s!=null){
                editText.setHint(s);
            }
            editText.setEms(attributes.getInt(R.styleable.PasswordEditText_ems,-1));
            Drawable background=attributes.getDrawable(R.styleable.PasswordEditText_editTextBackground);
            if(null != background){
                editText.setBackground(background);
            }
            CharSequence text=attributes.getText(R.styleable.PasswordEditText_text);
            if(null != text){
                editText.setText(text);
            }
            editText.setTextSize(TypedValue.COMPLEX_UNIT_PX,attributes.getDimension(R.styleable.PasswordEditText_textSize,18));
            ColorStateList colorStateList=attributes.getColorStateList(R.styleable.PasswordEditText_textColor);
            if(null != colorStateList){
                editText.setTextColor(colorStateList);
            }
            int drawable=attributes.getResourceId(R.styleable.PasswordEditText_editTextCursorBackground,0);
//        editText.setTextCursorDrawable(drawable);
            if(drawable != 0){
                try {
                    Field setCursor = TextView.class.getDeclaredField("mCursorDrawableRes");
                    setCursor.setAccessible(true);
                    setCursor.set(editText,drawable);
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            attributes.recycle();
        }

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!TextUtils.isEmpty(s)){
                    showPwd.setVisibility(View.VISIBLE);
                    clearPwd.setVisibility(View.VISIBLE);
                }else{
                    showPwd.setVisibility(View.GONE);
                    clearPwd.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        showPwd.setOnTouchListener(new View.OnTouchListener() {
            /* 按下图标时显示密码，抬起或移动到图标范围之外不明文显示密码 */
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //记录光标当前位置
                int cursorIndex=editText.getSelectionEnd();
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    if (hidePwd){
                        editText.getText().clear();
                        cursorIndex = 0;
                        hidePwd = false;
                    }else {
                        editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    }
//                    editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL){
//                    editText.setInputType(129);
                    editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                /**
                 *将光标设置为之前的位置
                 */
                editText.setSelection(cursorIndex);
                return true;
            }
        });

        clearPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.getText().clear();
            }
        });
    }

    public void setText(CharSequence charSequence){
        editText.setText(charSequence);
    }

    public String getText(){
        return editText.getText().toString();
    }

    public ImageView getShowPwdView(){
        return showPwd;
    }

    public void setSafeMode(boolean enable){
        this.hidePwd = enable;
    }
}
